package com.tianxin.workbao.workBao.Activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.internal.NavigationMenu;
import com.google.android.material.navigation.NavigationView;
import androidx.core.view.GravityCompat;
import androidx.core.view.MenuItemCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.SwitchCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.nispok.snackbar.SnackbarManager;
import com.nispok.snackbar.enums.SnackbarType;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.ContractStatistic;
import com.tianxin.workbao.workBao.bean.Role;
import com.tianxin.workbao.workBao.bean.Totalstatic;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.dataProvide.ContractProvide;
import com.tianxin.workbao.workBao.dataProvide.RoleProvide;
import com.tianxin.workbao.workBao.dataProvide.TotalStaticProvide;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.utils.common.SPUtils;
import com.tianxin.workbao.workBao.utils.common.TimeUtils;
import com.tianxin.workbao.workBao.utils.common.ToastUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;
import com.tianxin.workbao.workBao.view.ExpandView;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import io.github.yavski.fabspeeddial.FabSpeedDial;
import io.github.yavski.fabspeeddial.SimpleMenuListenerAdapter;
import lecho.lib.hellocharts.listener.PieChartOnValueSelectListener;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.view.PieChartView;

public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, UpdateListViewListener, View.OnClickListener {

    private FloatingActionButton mTopFab;
    private FabSpeedDial mFabSpeedDial;
    private TextView initRoleBtn;
    private RoleProvide roleProvide;
    private NavigationView mNavigationView;
    private View headerView;
    private SwitchCompat mSwitchCompat;
    private long firstTime;
    //contract statistic
    private ImageView contractArrow;
    private ExpandView contractExpandView;
    private PieChartView contractPieChartView;
    private ContractProvide contractProvide;
    private ContractStatistic mContractStatistic;
    private TextView contractLabelOne;
    private TextView contractLabelTwo;
    private TextView contractLabelThree;
    //coal statistic
    private TextView totalInWeightTv;
    private TextView totalInCarsTv;
    private TextView totalOutWeightTv;
    private TextView totalOutCarsTv;
    private TextView todayInWeightTv;
    private TextView todayInCarsTv;
    private TextView todayOutWeightTv;
    private TextView todayOutCarsTv;
    private TextView statisticTimeTv;
    private ImageView coalArrow;
    private ExpandView coalExpandView;
    private TotalStaticProvide totalStaticProvide;
    private Totalstatic mTotalstatic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        super.initStatusBar(true);
        initView();
        initData();
        initEvent();
        initRole();
    }


    public void initView() {
        mToolbar = findViewById(R.id.toolbar);
        mTopFab = findViewById(R.id.main_top_fab);
        mFabSpeedDial = findViewById(R.id.fabSpeedDial);
        mNavigationView = findViewById(R.id.nav_view);
        headerView = mNavigationView.getHeaderView(0);
        initRoleBtn = headerView.findViewById(R.id.init_role_btn);
        mToolbar.setTitle(R.string.company_sample_name);
        setSupportActionBar(mToolbar);
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        contractArrow = findViewById(R.id.arrow_contract);
        contractExpandView = findViewById(R.id.contract_expandView);
        contractPieChartView = findViewById(R.id.contract_pie);
        contractLabelOne = findViewById(R.id.contract_label_one);
        contractLabelTwo = findViewById(R.id.contract_label_two);
        contractLabelThree = findViewById(R.id.contract_label_three);

        totalInWeightTv = findViewById(R.id.total_in_weight);
        totalInCarsTv = findViewById(R.id.total_in_cars);
        totalOutWeightTv = findViewById(R.id.total_out_weight);
        totalOutCarsTv = findViewById(R.id.total_out_cars);
        todayInWeightTv = findViewById(R.id.today_in_weight);
        todayInCarsTv = findViewById(R.id.today_in_cars);
        todayOutWeightTv = findViewById(R.id.today_out_weight);
        todayOutCarsTv = findViewById(R.id.today_out_cars);
        coalArrow = findViewById(R.id.arrow_coal_yard);
        statisticTimeTv = findViewById(R.id.statistic_time);
        coalExpandView = findViewById(R.id.expandView_coal_yard);
        coalExpandView.setExpand(false);
    }

    @Override
    public void initData() {
        createContractPie();
        getTotalStaticProvide().getdatas();
    }

    //快速菜单
    @Override
    public void initEvent() {
        mFabSpeedDial.setMenuListener(new SimpleMenuListenerAdapter() {
            @SuppressLint("RestrictedApi")
            @Override
            public boolean onPrepareMenu(NavigationMenu navigationMenu) {
                if (getRoleProvide().hasRole(Constant.ROLE_MARKETING_SAMPLINGER)) {
                    navigationMenu.getRootMenu().findItem(R.id.action_sampling).setVisible(true);
                }
                if (getRoleProvide().hasRole(Constant.ROLE_GASSTATION_OILER)) {
                    navigationMenu.getRootMenu().findItem(R.id.action_add_oil).setVisible(true);
                }
                if (getRoleProvide().hasRole(Constant.ROLE_MARKETING_LOAD)) {
                    navigationMenu.getRootMenu().findItem(R.id.action_loadCar).setVisible(true);
                }
                return true;
            }

            @Override
            public boolean onMenuItemSelected(MenuItem menuItem) {
                int itemId = menuItem.getItemId();
                switch (itemId) {
                    case R.id.action_call:
                        Intent intent = new Intent(MainActivity.this, StaffContactActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.action_loadCar:
                        Intent loadCarIntent = new Intent(MainActivity.this, LoadCarEntranceActivity.class);
                        startActivity(loadCarIntent);
                        break;
                    case R.id.action_sampling:
                        startActivity(new Intent(MainActivity.this, SamplingActivity.class));
                        break;
                    case R.id.action_add_oil:
                        startActivity(new Intent(MainActivity.this, AddOilActivity.class));
                        break;
                }
                return false;
            }
        });
        mTopFab.setOnClickListener(this);
        contractArrow.setOnClickListener(this);
        coalArrow.setOnClickListener(this);
        initRoleBtn.setOnClickListener(this);
    }

    @Override
    public void bindView() {

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = secondTime;
            } else {
                super.onBackPressed();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        switch (id) {
            case R.id.action_settings:

                break;
            case R.id.action_scan:

                break;
            case R.id.action_Share:
                UIUtils.share(this, getResources().getString(R.string.app_name_zh), null);
                break;
        }


        return super.onOptionsItemSelected(item);
    }

    // left menu
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        switch (id) {
            case R.id.nav_camera:
                break;
            case R.id.nav_wash_coal_report:
                startActivity(new Intent(MainActivity.this, WashReportActivity.class));
                break;
            case R.id.nav_test:
                startActivity(new Intent(MainActivity.this, TestActivity.class));
                break;
            case R.id.nav_share:
                startActivity(new Intent(MainActivity.this, AppShareActivity.class));
                break;
            case R.id.nav_quit:
                super.quitApp();
                break;
            case R.id.nav_back_bill:
                startActivity(new Intent(MainActivity.this, BackBillEntranceActivity.class));
                break;
            case R.id.nav_bill_oauth:
                startActivity(new Intent(MainActivity.this, BillDataOauthActivity.class));
                break;
            case R.id.nav_base_data:
                startActivity(new Intent(MainActivity.this, BaseDataActivity.class));
                break;
            case R.id.nav_input_data:
                startActivity(new Intent(MainActivity.this, InputDataActivity.class));
                break;
            case R.id.nav_output_data:
                startActivity(new Intent(MainActivity.this, OutputDataActivity.class));
                break;
            case R.id.nav_coal_storage_data:
                startActivity(new Intent(MainActivity.this, CoalStorageActivity.class));
                break;
            case R.id.nav_contract:
                startActivity(new Intent(MainActivity.this, ContractActivity.class));
                break;
            case R.id.nav_trans_contract_data:
                startActivity(new Intent(MainActivity.this, TransContractActivity.class));
                break;
            case R.id.nav_coal_money:
                startActivity(new Intent(MainActivity.this, CoalMoneyActivity.class));
                break;
            case R.id.nav_coal_money_calc:
                startActivity(new Intent(MainActivity.this, CoalMoneyCalcActivity.class));
                break;
            case R.id.nav_car_finance:
                startActivity(new Intent(MainActivity.this, CarMoneyActivity.class));
                break;
            case R.id.nav_car_finance_search:
                startActivity(new Intent(MainActivity.this, CarMoneySearchActivity.class));
                break;
            case R.id.nav_car_finance_static:
                startActivity(new Intent(MainActivity.this, CarMoneyStatisticActivity.class));
                break;
            case R.id.nav_coal_statistic:
                startActivity(new Intent(MainActivity.this, CoalStatisticActivity.class));
                break;
            case R.id.nav_application_data:
                startActivity(new Intent(MainActivity.this, AppDataManagerActivity.class));
                break;
        }
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    private void initNavView() {
        boolean isNight = SPUtils.getPrefBoolean(Constant.THEME_MODEL, false);
        if (isNight) {
            getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        } else {
            getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        }
        MenuItem item = mNavigationView.getMenu().findItem(R.id.nav_night);
        // permission controller
        RoleProvide roleProvide = getRoleProvide();
        //wash report
        if (roleProvide.hasRole(Constant.ROLE_WASH_ADMIN)) {
            mNavigationView.getMenu().findItem(R.id.nav_wash_coal_report).setVisible(true);
        }
        //back bill
        if (roleProvide.hasRole(Constant.ROLE_MARKETING_BACK_BILL)) {
            mNavigationView.getMenu().findItem(R.id.nav_back_bill).setVisible(true);
        }
        //test bill input
        if (roleProvide.hasRole(Constant.ROLE_MARKETING_TEST_ADMIN)
                || roleProvide.hasRole(Constant.ROLE_MARKETING_TESTER)) {
            mNavigationView.getMenu().findItem(R.id.nav_test).setVisible(true);
        }
        //marketing menu
        if (roleProvide.hasRole(Constant.ROLE_MARKETING)) {
            mNavigationView.getMenu().findItem(R.id.marketing_menu).setVisible(true);

            if (roleProvide.hasRole(Constant.ROLE_MARKETING_ADMIN)
                    || roleProvide.hasRole(Constant.ROLE_MARKETING_SALES_MANAGER)
                    || roleProvide.hasRole(Constant.ROLE_MARKETING_SALES_ASSISTANT)) {
                mNavigationView.getMenu().findItem(R.id.nav_contract).setVisible(true);
                mNavigationView.getMenu().findItem(R.id.nav_coal_money).setVisible(true);
                mNavigationView.getMenu().findItem(R.id.nav_coal_money_calc).setVisible(true);
                mNavigationView.getMenu().findItem(R.id.nav_coal_storage_data).setVisible(true);
                mNavigationView.getMenu().findItem(R.id.nav_coal_statistic).setVisible(true);
            }
            if (roleProvide.hasRole(Constant.ROLE_MARKETING_ADMIN)
                    || roleProvide.hasRole(Constant.ROLE_MARKETING_CASHIER)) {
                mNavigationView.getMenu().findItem(R.id.nav_coal_money).setVisible(true);
            }
            if (roleProvide.hasRole(Constant.ROLE_MARKETING_WEIGHER)) {
                mNavigationView.getMenu().findItem(R.id.nav_bill_oauth).setVisible(true);
            }
        }
        //transport menu
        if (roleProvide.hasRole(Constant.ROLE_TRANS)) {
            mNavigationView.getMenu().findItem(R.id.trans_menu).setVisible(true);

            if (roleProvide.hasRole(Constant.ROLE_MARKETING_TEST_ADMIN)
                    || roleProvide.hasRole(Constant.ROLE_TRANS_FREIGHT_CLERK)) {
                mNavigationView.getMenu().findItem(R.id.nav_trans_contract_data).setVisible(true);
                mNavigationView.getMenu().findItem(R.id.nav_car_finance).setVisible(true);
                mNavigationView.getMenu().findItem(R.id.nav_car_finance_search).setVisible(true);
            }
            if (roleProvide.hasRole(Constant.ROLE_MARKETING_TEST_ADMIN)) {
                mNavigationView.getMenu().findItem(R.id.nav_car_finance_static).setVisible(true);
            }
        }
        mNavigationView.getMenu().findItem(R.id.nav_night).setChecked(true);
        mSwitchCompat = MenuItemCompat.getActionView(item).findViewById(R.id.night_view_switch);
        mSwitchCompat.setChecked(isNight);
        mSwitchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                SPUtils.setPrefBoolean(Constant.THEME_MODEL, b);
                mSwitchCompat.setChecked(b);
                if (b) {
                    getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                } else {
                    getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                }
            }
        });

        CircleImageView userHeader = headerView.findViewById(R.id.curr_user_header);
        userHeader.setOnClickListener(this);
        TextView userName = headerView.findViewById(R.id.curr_user_name);
        TextView userWork = headerView.findViewById(R.id.curr_user_work);
        String headerUrl = SPUtils.getPrefString(Constant.CURRENT_USER_HEADER, null);
        if (headerUrl != null && headerUrl.length() > 10) {
            Glide.with(MainActivity.this).load(headerUrl).into(userHeader);
        }
        userName.setText(SPUtils.getPrefString(Constant.CURRENT_USER_NAME, "姓名"));
        userWork.setText(
                SPUtils.getPrefString(Constant.CURRENT_USER_PORG_NAME, "") + "  " +
                        SPUtils.getPrefString(Constant.CURRENT_USER_ORG_NAME, ""));
    }

    //initialize contract pie chart view
    private void createContractPie() {
        getContractProvide().statistic();
    }

    private void initContractPieView() {
        if (mContractStatistic != null) {
            List<SliceValue> values = new ArrayList<>();

            SliceValue value = new SliceValue();
            value.setValue(mContractStatistic.getBuyContracts());
            value.setColor(getResources().getColor(R.color.recycler_color1));
            value.setLabel(mContractStatistic.getBuyContractStr());
            values.add(value);

            SliceValue value1 = new SliceValue();
            value1.setValue(mContractStatistic.getSaleContracts());
            value1.setColor(getResources().getColor(R.color.recycler_color2));
            value1.setLabel(mContractStatistic.getSaleContractStr());
            values.add(value1);

            SliceValue value2 = new SliceValue();
            value2.setValue(mContractStatistic.getTransContracts());
            value2.setColor(getResources().getColor(R.color.recycler_color3));
            value2.setLabel(mContractStatistic.getTransContractStr());
            values.add(value2);

            PieChartData contractData = new PieChartData();
            contractData.setValues(values);
            contractData.setHasLabelsOutside(true);
            contractData.setHasCenterCircle(false);
            contractData.setSlicesSpacing(1);
            contractPieChartView.setPieChartData(contractData);

            contractPieChartView.setCircleFillRatio(1);
            contractPieChartView.setChartRotation(45, true);
            contractPieChartView.setChartRotationEnabled(false);
            contractPieChartView.setOnValueTouchListener(getValueSelectListener());
            contractExpandView.setExpand(true);
            contractLabelOne.setText(mContractStatistic.getBuyContractStr().replace(" ", ""));
            contractLabelTwo.setText(mContractStatistic.getSaleContractStr().replace(" ", ""));
            contractLabelThree.setText(mContractStatistic.getTransContractStr().replace(" ", ""));
        } else {
            showMessage("获取合同统计信息失败！");
        }
    }

    private void setTotalStatisticData() {
        totalInWeightTv.setText(mTotalstatic.getTotalinputweight() + "");
        totalInCarsTv.setText(mTotalstatic.getTotalinputcarnum() + "");
        totalOutWeightTv.setText(mTotalstatic.getTotaloutputweight() + "");
        totalOutCarsTv.setText(mTotalstatic.getTotaloutputcarnum() + "");
        todayInWeightTv.setText(mTotalstatic.getTodayinputweight() + "");
        todayInCarsTv.setText(mTotalstatic.getTodayinputcarnum() + "");
        todayOutWeightTv.setText(mTotalstatic.getTodayoutputweight() + "");
        todayOutCarsTv.setText(mTotalstatic.getTodayoutputcarnum() + "");
        statisticTimeTv.setText(TimeUtils.parseDateTime(mTotalstatic.getLastaddtime()));
    }

    @Override
    public void showMessage(String msg) {
        ToastUtils.showLong(msg);
    }

    @Override
    public void showProgress() {
        getSweetAlertDialog(this).showDialog("", 1200);
    }

    @Override
    public void hideProgress() {
        getSweetAlertDialog(this).dismiss();
    }

    @Override
    public void onRefreshData(Object result) {
        if (result instanceof ContractStatistic) {
            mContractStatistic = (ContractStatistic) result;
            initContractPieView();
        } else if (result instanceof Totalstatic) {
            mTotalstatic = (Totalstatic) result;
            setTotalStatisticData();
        } else if (result instanceof Role) {
            initNavView();
        }
    }

    @Override
    public void onLoadMoreData(Object result) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_top_fab:
                if (getRoleProvide().hasRole(Constant.ROLE_MARKETING_ADMIN) ||
                        getRoleProvide().hasRole(Constant.ROLE_TRANS_ADMIN)) {
                    startActivity(new Intent(MainActivity.this, StatisticActivity.class));
                } else {
                    showMessage("你无权操作！");
                }
                break;
            case R.id.arrow_contract:
                handleExpendView(contractExpandView, contractArrow);
                break;
            case R.id.arrow_coal_yard:
                handleExpendView(coalExpandView, coalArrow);
                break;
            //init role menu
            case R.id.init_role_btn:
                initRole();
                break;
            case R.id.curr_user_header:
                startActivity(new Intent(MainActivity.this, AlertPasswordActivity.class));
                break;
        }
    }

    /**
     * init role
     */
    private void initRole() {
        getRoleProvide().updateRole();
    }

    public ContractProvide getContractProvide() {
        if (contractProvide == null) {
            contractProvide = new ContractProvide(this, this);
        }
        return contractProvide;
    }

    public TotalStaticProvide getTotalStaticProvide() {
        if (totalStaticProvide == null) {
            totalStaticProvide = new TotalStaticProvide(this, this);
        }
        return totalStaticProvide;
    }

    public PieChartOnValueSelectListener getValueSelectListener() {
        PieChartOnValueSelectListener listener = new PieChartOnValueSelectListener() {
            @Override
            public void onValueSelected(int arcIndex, final SliceValue value) {
                com.nispok.snackbar.Snackbar snackBar =
                        com.nispok.snackbar.Snackbar
                                .with(MainActivity.this)
                                .type(SnackbarType.MULTI_LINE)
                                .duration(com.nispok.snackbar.Snackbar.SnackbarDuration.LENGTH_SHORT)
                                .position(com.nispok.snackbar.Snackbar.SnackbarPosition.BOTTOM)
                                .margin(15, 15)
                                .backgroundDrawable(R.color.colorPrimary)
                                .text(String.valueOf(value.getLabel()))
                                .textColor(Color.WHITE)
                                .actionLabel("查看")
                                .actionColor(Color.WHITE)
                                .actionListener(sb -> Toast.makeText(MainActivity.this, String.valueOf(value.getLabel()), Toast.LENGTH_SHORT).show());

                SnackbarManager.show(snackBar);
            }

            @Override
            public void onValueDeselected() {

            }
        };
        return listener;
    }

    public RoleProvide getRoleProvide() {
        if (roleProvide == null) {
            roleProvide = new RoleProvide(this, this);
        }
        return roleProvide;
    }
}
